package cn.zetark.oauth2.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import com.ls.fw.auth.oauth2.as.service.OAuthService;

/**
 */
@Service("oAuthService")
public class OAuthServiceImpl implements OAuthService {

    private Cache code_cache;
    private Cache token_cache;
    private Cache refresh_token_cache;
    
    private Map<String,String> map = new HashMap<String,String>();
    {
    	map.put("c1ebe466-1cdc-4bd3-ab69-77c3561b9dee", "d8346ea2-6017-43ed-ad68-19c0f971738b");
    }
    @Autowired
    public OAuthServiceImpl(CacheManager cacheManager) {
        this.code_cache = cacheManager.getCache("code-cache");
        this.token_cache = cacheManager.getCache("token-cache");
        this.refresh_token_cache = cacheManager.getCache("refresh-token-cache");
    }

    @Override
    public void addAuthCode(String authCode, String username) {
        code_cache.put(authCode, username);
    }

    @Override
    public void removeAuthCode(String authCode) {
        code_cache.evict(authCode);
    }

    @Override
    public void addAccessToken(String accessToken, String username) {
        token_cache.put(accessToken, username);
    }

    @Override
    public void addRefreshToken(String refreshToken, String accessToken) {
        refresh_token_cache.put(refreshToken, accessToken);
    }
    @Override
    public String getUsernameByAuthCode(String authCode) {
        return (String)code_cache.get(authCode).get();
    }

    @Override
    public String getUsernameByAccessToken(String accessToken) {
        return (String)token_cache.get(accessToken).get();
    }

    @Override
    public String getAccessTokenByRefreshToken(String refreshToken) {
        return (String)refresh_token_cache.get(refreshToken).get();
    }
    @Override
    public boolean checkAuthCode(String authCode) {
        return code_cache.get(authCode) != null;
    }

    @Override
    public boolean checkAccessToken(String accessToken) {
        return token_cache.get(accessToken) != null;
    }

    @Override
    public boolean checkRefreshToken(String refreshToken) {
        return this.refresh_token_cache.get(refreshToken) != null;
    }

    @Override
    public boolean checkClientId(String clientId) {
        return map.get(clientId)!=null;
    }

    @Override
    public boolean checkClientSecret(String clientId,String clientSecret) {
        String b = map.get(clientId);
        return b.equals(clientSecret);
    }

    @Override
    public long getExpireIn(String clientId) {
        return 7200L;
    }
}
